const express = require('express')
const bodyparser = require('body-parser');
const path = require('path')
const fs = require("fs");
const formidable=require('formidable');
const COS = require('cos-nodejs-sdk-v5');
const standard_router = require('./module/standard/index')
const auth_router = require('./module/auth/index')
const member_router = require('./module/member/index')
const app = express();


//设置跨域访问
app.all('*', (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    next();
});
app.use(bodyparser.json())
app.use(express.static('public'));


var cos = new COS({
    AppId: '1253860470',
    SecretId: 'AKIDWv9MTOhcw4xrdFvy77wYyBD5lEVefGoC',
    SecretKey: 'KUWO3WmqhMo494nOn05yfDbnnaBanpne',
});

// 图片上传
app.post('/api/uploadFile', function(req, res, next){
    // 文件路径
    var form = new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        if(err){
            res.send({
                code :'500',
                message:'图片上传失败',
            })
            return 
        }else{
            const ROON = path.dirname(__dirname)
            const PUBLIC = path.join(ROON,'serverData','public','images');
            const IMAGE = path.join(PUBLIC);
            if (!fs.existsSync(IMAGE)) {
                fs.mkdirSync(IMAGE)
            }
            if(files.img.size>10485760){
                res.send({
                    code :'500',
                    message:'上传的图片不能超过10M',
                })
                return
            }
            
            let img_name = files.img.originalFilename;
            let read = fs.createReadStream(files.img.filepath);
            let write = fs.createWriteStream(path.join(IMAGE, img_name));
            read.pipe(write);
            read.on('end',(data)=>{
                let imagePath = './public/images'+'/'+img_name;
                cos.sliceUploadFile({
                    Bucket:'test-1253860470',
                    Region: 'ap-nanjing',
                    Key:img_name,
                    FilePath:imagePath

                },function(err,data){
                    console.log(data)
                    if(!err){
                        console.log(data['Location']);
                        fs.rm(imagePath,function(data){
                            console.log(data)
                        });
                        res.send({
                            code :'200',
                            message:'上传成功',
                            src: 'https://'+data['Location']
                        })
                    }else{
                        console.log(err,'<==>');
                    }
                })
            })
        }
    })

})



/*图片上传*/
// app.post('/api/uploadFile',(req,res)=>{
//     var form = new formidable.IncomingForm();
//     form.parse(req,function(err,fields,files){
//         if(err){
//             res.send({
//                 code :'500',
//                 message:'图片上传失败',
//             })
//             return 
//         }else{
//             const ROON = path.dirname(__dirname)
//             const PUBLIC = path.join(ROON,'server','public','images');
//             const IMAGE = path.join(PUBLIC);
//             if (!fs.existsSync(IMAGE)) {
//                 fs.mkdirSync(IMAGE)
//             }
//             console.log(files.img.size)
//             if(files.img.size>10485760){
//                 res.send({
//                     code :'500',
//                     message:'上传的图片不能超过10M',
//                 })
//                 return
//             }
            
//             let img_name = files.img.originalFilename;
//             let read = fs.createReadStream(files.img.filepath);
//             let write = fs.createWriteStream(path.join(IMAGE, img_name));
//             read.pipe(write);
//             let origin = req.headers.origin;
//             res.send({
//                 code :'200',
//                 message:'上传成功',
//                 src: `http://localhost:3000/images/${img_name}`
//             })
            
//         }
//     })

// })
/*图片上传*/




app.use(`/api`,standard_router)
app.use(`/api`,auth_router)
app.use(`/api`,member_router)

//配置服务端口 
app.listen(3000, () => {
    const hostname = 'localhost';
    const port = 3000;
    // console.log(`Server running at http://${hostname}:${port}/`);
})
